package com.gupao.vip.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable {
    private int port;

    private CountDownLatch latch;

    private AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port){
        this.port = port;
        try{
            //1.创建一个异步的服务端通道AsynchronousServerSocketChannel
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();

            /**
             * 2.调用AsynchronousServerSocketChannel对象的bind方法绑定监听端口
             * 如果端口合法且没被占用，绑定成功，打印启动成功提示到控制台
             */
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port :" + port);
        }catch(IOException e){
            System.err.println(e.getMessage());
        }
    }
    @Override
    public void run() {
        //在完成一组正在执行的操作之前，允许当前的线程一直阻塞
        latch = new CountDownLatch(1);

        //接收客户端的连接，由于是异步操作，我们可以传递一个CompletionHandler<AsynchronousSocketChannel, ? super A>类型的handler实例接收accept操作成功的通知消息
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
        try {
            latch.await();
        } catch (InterruptedException e) {
            System.err.println(e.getMessage());
        }
    }

    public AsynchronousServerSocketChannel getAsynchronousServerSocketChannel() {
        return asynchronousServerSocketChannel;
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}
